<template>
    <view class="content" v-if="isShow" @click.stop="isShow=false">
        <!-- <canvas @click.stop="" :style="{ width: canvasW + 'px', height: canvasH + 'px', background: `url(${backgroundImg})`, 'background-size': '100% 100%'  }" canvas-id="my-canvas"></canvas> -->
		<canvas @click.stop="" :style="{ width: canvasW + 'px', height: canvasH + 'px','background-size': '100% 100%'  }" canvas-id="my-canvas"></canvas>
        <view class="save-btn" @click.stop="saveImage">保存图片</view>
    </view>
</template>

<script>

    export default {
      props: {
        headerImg: {
          type: String,
          default: ''
        },
        title: {
          type: String,
          default: ''
        },
        subTitle: {
          type: String,
          default: ''
        },
        price: {
          type: Number,
          default: 0
        },
        content: {
          type: String,
          default: ""
        },
        abImg: {
          type: String,
          default: ''
        }
      },
      data() {
        return {
          canvasW: 0,
          canvasH: 0,
          ctx: null,
          isShow: false,
          qrcode: '',
          headerImg: '',
          backgroundImg: ''
        }
      },
      methods: {
        //显示
        showCanvas(backgroundImg, headerImg, qrcode) {
          this.isShow = true
          this.qrcode = qrcode
          this.headerImg = headerImg
          this.backgroundImg = backgroundImg
          this.__init()
        },

        //初始化画布
        async __init() {
          uni.showLoading({
            title: '加载中...',
            mask: true
          })
          this.ctx = uni.createCanvasContext('my-canvas', this)
          this.canvasW = uni.upx2px(550);
          this.canvasH = uni.upx2px(900);
          //设置画布背景透明
          this.ctx.setFillStyle('rgba(255, 255, 255, 0)')
          //设置画布大小
          this.ctx.fillRect(0, 0, this.canvasW, this.canvasH)
          //绘制圆角背景
          let base64_bg = await this.urlToBase64(this.backgroundImg)
          const bgImgPath = wx.env.USER_DATA_PATH + "/bg" + new Date().getTime() + "" + ".png";
          const bgFile = wx.getFileSystemManager();
          bgFile.writeFileSync(bgImgPath, base64_bg, "base64");
          this.ctx.drawImage(bgImgPath, //图像资源
              0,
              0,
              this.canvasW,
              this.canvasH
          )

          let base64_ad = await this.urlToBase64(this.headerImg)
          const adImgPath = wx.env.USER_DATA_PATH + "/header" + new Date().getTime() + "" + ".png";
          const adFile = wx.getFileSystemManager();
          adFile.writeFileSync(adImgPath, base64_ad, "base64");
          const bottomImgX = (this.canvasW - uni.upx2px(300)) / 2
          this.ctx.drawImage(adImgPath, bottomImgX, uni.upx2px(280), uni.upx2px(300), uni.upx2px(250))

          /**
           * 绘制二维码
           */
          const qrCodeX = (this.canvasW - uni.upx2px(200)) / 2
          this.ctx.drawImage(this.qrcode, qrCodeX, uni.upx2px(630), uni.upx2px(200), uni.upx2px(200))

          /**
           * 绘制标题
           */
          if(this.title) {
            console.log('title=', this.title)
            this.ctx.setFontSize(14); //设置标题字体大小
            this.ctx.setFillStyle('#333'); //设置标题文本颜色
            const titleWidth = this.ctx.measureText(this.title).width
            const maxWidth = uni.upx2px(410)
            const ellipsis = '...'
            const ellipsisWidth = this.ctx.measureText(ellipsis).width

            let actualText = this.title
            if (titleWidth > maxWidth - ellipsisWidth) {
              const visibleWidth = maxWidth - ellipsisWidth
              const characters = this.title.split('')
              while (this.ctx.measureText(characters.join('')).width > visibleWidth && characters.length > 0) {
                characters.pop()
              }
              actualText = characters.join('') + ellipsis;
            }
            const titleActualWidth = this.ctx.measureText(actualText).width
            const titleX = (this.canvasW - titleActualWidth) / 2
            this.ctx.fillText(actualText, titleX, uni.upx2px(200))
          }
          /**
           * 绘制价格
           */
          if (this.content) {
            //console.log(this.content)
            this.ctx.setFontSize(14);
            this.ctx.setFillStyle('#999');
            this.ctx.setFontSize(12);
            const maxWidth = uni.upx2px(410)
            const ellipsis = '...'
            const ellipsisWidth = this.ctx.measureText(ellipsis).width
            const contextWidth = this.ctx.measureText(this.content).width
            let actualContentText = this.content
            if (contextWidth > maxWidth - ellipsisWidth) {
              const visibleContentWidth = maxWidth - ellipsisWidth
              const contentCharacters = this.content.split('')
              while (this.ctx.measureText(contentCharacters.join('')).width > visibleContentWidth && contentCharacters.length > 0) {
                contentCharacters.pop()
              }
              actualContentText = contentCharacters.join('') + ellipsis;
            }
            const contentActualWidth = this.ctx.measureText(actualContentText).width
            const contentX = (this.canvasW - contentActualWidth) / 2
            this.ctx.fillText(actualContentText, contentX, uni.upx2px(570))
          }

          //延迟渲染
          setTimeout(() => {
            this.ctx.draw(true, () => {
              uni.hideLoading()
            })
          }, 500)

        },

        /**
         * url转base64
         * @param url
         * @returns {string}
         */
        urlToBase64(imageUrl) {
          return new Promise((resolve, reject) => {
            wx.request({
              url: imageUrl,
              responseType: 'arraybuffer',
              success: function(res) {
                const base64 = wx.arrayBufferToBase64(res.data);
                resolve(base64);
              },
              fail: function(error) {
                console.error('转换失败', error);
                reject(error);
              }
            });
          });
        },

        //保存图片到相册
        saveImage() {
          var that = this
          uni.showLoading({
            title: '正在加载',
            mask: false
          });
          uni.canvasToTempFilePath({
            canvasId: 'my-canvas',
            quality: 1,
            complete: (res) => {
              console.log('保存到相册', res);
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                  uni.hideLoading();
                  uni.showToast({
                    title: '已保存到相册',
                    icon: 'success',
                    duration: 2000
                  })
                  setTimeout(() => {
                    that.isShow = false
                  }, 2000)
                }
              })
            }
          }, this);
        }
      }
    }
</script>

<style scoped lang="scss">
.content{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999999;
    background: rgba(0,0,0,.4);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .save-btn{
        margin-top: 35rpx;
        color: #FFFFFF;
        background: linear-gradient(to right, #FE726B , #FE956B);
        padding: 15rpx 40rpx;
        border-radius: 50rpx;
    }
}
</style>
